import { defineStore } from 'pinia'
import { CloudStoreType } from './index.d'
import SocketPlugin from '@/utils/cloud/socket/webSocket.js'
import PreviewAPI from '@/api/preview'
import useStorage from '@/hooks/cloud/storage'
import { isEdge } from '@/utils'
const { getStorage, setStorage } = useStorage()

export const useCloudStore = defineStore({
  id: 'useCloudStore',
  state: (): CloudStoreType => ({
    socket: null,
    operation_password: ''
  }),
  getters: {
    getSocket(): any {
      
      return new Promise((resolve, inject) => {
        if (isEdge()){
          resolve(null)
          return
        }
        let timeout = setInterval(() => {
          if (this.socket) {
            resolve(this.socket)
            clearInterval(timeout)
          }
        }, 100)
      })
    },
    getOperationPassword(): string {
      return this.operation_password
    }
  },
  actions: {
    async createSocket() {
      let socket = null
      socket = new SocketPlugin()
      await socket.connect()
      this.socket = socket
    },
    async setOperationPassword(pwd?: any) {
      if (pwd) {
        setStorage('operation_password', pwd)
        return
      }
      const storagePassword = getStorage('operation_password')
      if (storagePassword) {
        this.operation_password = storagePassword
      }
      const stationRes = await PreviewAPI.getDeviceTags({
        recursive: true,
        root_id: getStorage('activeSiteId'),
        target_category: 'energy_subsystem'
      })
      if (stationRes.msg[0] && stationRes.msg[0].item_extra_content) {
        const extra_content = JSON.parse(stationRes.msg[0].item_extra_content)
        if (extra_content.operation_password) {
          this.operation_password = extra_content.operation_password
        }
      }
      this.operation_password = import.meta.env.VITE_GLOB_APP_DEFAULT_OPERATION_PASSWORD || '1234'
    }
  }
})
